﻿--添加新结点
CREATE PROCEDURE [dbo].[proc_zzjg_xx_Create]
	(
	 @CompanyName nvarchar(50),
	 @Startletter nvarchar(50),	
	 @CompanyPhone nvarchar(50),
	 @CompanyFax nvarchar(50),
	 @CompanyAddress nvarchar(200),
	 @Zip nvarchar(10),
	 @ContactPerson nvarchar(20),
	 @ContactPhone nvarchar(20),
	 @ContactEmail nvarchar(50),
	 @WebAddress nvarchar(50),
	 @Products nvarchar(2000),
	 @id INT,
	 @sort VARCHAR(50)
	)
AS
	begin 

BEGIN TRANSACTION--开始事务
DECLARE @errorSun INT --定义错误计数器
SET @errorSun=0 --没错为0
                --
---------生成新编号 BEGIN--------
DECLARE @bh VARCHAR(50)
set @bh=ISNULL (( select top 1 bh FROM zzjg where pid=@id ORDER BY bh desc),'') --同级别已存在的编号
IF @bh='' --第一级
BEGIN
   DECLARE @bh_s VARCHAR(50) 
   select @bh_s= bh FROM zzjg where id=@id 
   SET @bh=@bh_s+'01'
END
ELSE
	BEGIN
		DECLARE @a VARCHAR(50),@b int
		SET @a=RIGHT(@bh,2)
		SET @b=CONVERT(INT,@a)+1
		IF @b<10
		BEGIN
			SET @bh=LEFT(@bh,LEN(@bh)-2)+'0'+CONVERT(VARCHAR,@b)
		END
		ELSE
			BEGIN
				SET @bh=LEFT(@bh,LEN(@bh)-2)+CONVERT(VARCHAR,@b)
			END
	END
---------生成新编号 END--------

		INSERT INTO zzjg
		(
			
			pid,
			name,
			[level],
			sort,
			bh,
			flag
		)
		SELECT 
		
			@id,
			@CompanyName,
			 [LEVEL]+1,
			@sort,
			@bh,
			0
	FROM zzjg WHERE id=@id
	
	           
  if @@ROWCOUNT<1
	begin
		set @errorSun=@errorSun+1		
		goto e;
	END
	
	DECLARE @nid INT
	set @nid =isnull(@@Identity ,0)

	INSERT INTO ManagementArea(CompanyName,Startletter,CompanyPhone,CompanyFax,CompanyAddress,Zip,
	ContactPerson,ContactPhone,ContactEmail,WebAddress,Products,zid,flag,CompanyNumber)
		Values(@CompanyName,@Startletter,@CompanyPhone,@CompanyFax,@CompanyAddress,@Zip,
		@ContactPerson,@ContactPhone,@ContactEmail,@WebAddress,@Products,@bh,0,@sort)
	
           
  if @@ROWCOUNT<1
	begin
		set @errorSun=@errorSun+1		
		goto e;
	END
	Select isnull(@@Identity ,0) as 'RETUNR_V'
e:
    PRINT @errorSun
	if @errorSun>0
	begin
		rollback TRANSACTION	
	end
	else
	begin
		commit TRANSACTION
	END
	
	end
	RETURN

